/*
 * ir_detect.c
 *
 *  Created on: 2017年5月6日
 *      Author: chenss
 */

#include "io/ir_detect.h"
#include "io.h"

static int _status;

static void _EXTI13N14_Config(void);

void IrDetect_Init(void)
{
    _EXTI13N14_Config();

    _status = IrDetect_Get();
}

static void _EXTI13N14_Config(void)
{
    EXTI_InitTypeDef EXTI_InitStructure;
    GPIO_InitTypeDef GPIO_InitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    /* Enable GPIOC clock */
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);

    /* Enable SYSCFG clock */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

    /* Configure pins as input floating */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_1;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOB, EXTI_PinSource13);
    SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOB, EXTI_PinSource14);

    EXTI_InitStructure.EXTI_Line = EXTI_Line13 | EXTI_Line14;
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);

//    EXTI_InitStructure.EXTI_Line = EXTI_Line14;
//    EXTI_Init(&EXTI_InitStructure);

    /* Enable and set EXTI4_15 Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = EXTI4_15_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPriority = 0x01;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

void IrDetect_Exti13N14Handler(void)
{
    int status;
    bool changed = FALSE;

    if(EXTI_GetITStatus(EXTI_Line13) != RESET)
    {
        changed = TRUE;
        EXTI_ClearITPendingBit(EXTI_Line13);
    }

    if(EXTI_GetITStatus(EXTI_Line14) != RESET)
    {
        changed = TRUE;
        EXTI_ClearITPendingBit(EXTI_Line13);
    }

    if(changed)
    {
        status = IrDetect_Get();
        if(status != _status)
        {
            _status = status;
            IO_Changed(IO_IrDetectStatus, status);
        }
    }

}

int IrDetect_Get(void)
{
    BitAction ir1, ir2;

    ir1 = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_13);
    ir2 = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14);
    return ((ir1 == Bit_RESET) || (ir2 == Bit_RESET)) ? 1 : 0;
}
